# -*- coding: utf-8 -*-
# @Time: 2025/11/9 9:43
# @Author: subencai
# @Email: 2080981057@qq.com
# @File: teacher.py
# @Project: flaskProject
# @Description:
# router/teacher/teacher.py（RESTful 接口实现）


# from . import teacher_bp
# from flask_restful import Api, Resource
# from flask import request
# from Lib.resp import my_response
#
# # 模拟老师数据的内存存储（字典结构）
# teachers = {
#     1: {"name": "张教授", "age": 45, "subject": "计算机科学"},
#     2: {"name": "李教授", "age": 50, "subject": "软件工程"}
# }
# next_id = 3  # 用于生成新老师的ID
#
#
# # 初始化flask-restful的Api
# api = Api(teacher_bp)
#
# class Teacher(Resource):
#     # 1. 查询老师（单个/全部）
#     def get(self, id=None):
#         if id:
#             # 查单个老师
#             teacher = teachers.get(id)
#             if not teacher:
#                 return my_response(code=404, message=f"ID为{id}的老师不存在")
#             return my_response(data=teacher, message="查询成功")
#         else:
#             # 查全部老师
#             return my_response(data=teachers, message="查询全部成功")
#
#     # 2. 新增老师
#     def post(self):
#         global next_id
#         data = request.get_json()
#         if not data or not data.get("name"):
#             return my_response(code=400, message="姓名不能为空")
#         new_teacher = {
#             "name": data.get("name"),
#             "age": data.get("age", 0),
#             "subject": data.get("subject", "未知")
#         }
#         teachers[next_id] = new_teacher
#         current_id = next_id
#         next_id += 1
#         return my_response(data={"id": current_id, **new_teacher}, message="新增成功")
#
#     # 3. 更新老师信息
#     def put(self, id):
#         if id not in teachers:
#             return my_response(code=404, message=f"ID为{id}的老师不存在")
#         data = request.get_json()
#         if not data:
#             return my_response(code=400, message="更新数据不能为空")
#         teachers[id].update(data)
#         return my_response(data=teachers[id], message=f"ID为{id}的老师更新成功")
#
#     # 4. 删除老师
#     def delete(self, id):
#         if id not in teachers:
#             return my_response(code=404, message=f"ID为{id}的老师不存在")
#         deleted = teachers.pop(id)
#         return my_response(data=deleted, message=f"ID为{id}的老师删除成功")
#
#
# # 注册老师接口的路由
# api.add_resource(Teacher, "/teacher")  # 对应GET(查全部)、POST(新增)
# api.add_resource(Teacher, "/teacher/<int:id>", endpoint="teacherid")  # 对应GET(查单个)、PUT、DELETE


from . import teacher_bp  # 导入老师蓝图
from flask_restful import Api, Resource, reqparse
from models import Teacher  # 导入老师模型
from server import db  # 导入数据库实例
from Lib.resp import my_response  # 统一响应格式

api = Api(teacher_bp)

# 解析请求参数（针对老师的字段）
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True, help='姓名不能为空')
parser.add_argument('age', type=int)
parser.add_argument('subject', type=str)  # 老师的“学科”字段，对应学生的“major”


class TeacherResource(Resource):
    # 获取所有老师（GET /teacher/teacher）
    def get(self):
        teachers = Teacher.query.all()  # 从数据库查询所有老师
        # 构造返回数据（id作为键，信息作为值）
        data = {str(t.id): {'name': t.name, 'age': t.age, 'subject': t.subject} for t in teachers}
        return my_response(code=200, message='查询成功', data=data)

    # 新增老师（POST /teacher/teacher）
    def post(self):
        args = parser.parse_args()  # 解析请求参数
        new_teacher = Teacher(
            name=args['name'],
            age=args['age'],
            subject=args['subject']
        )
        db.session.add(new_teacher)  # 添加到数据库会话
        db.session.commit()  # 提交事务（写入数据库）
        return my_response(code=201, message='新增成功', data={'id': new_teacher.id})


class TeacherSingleResource(Resource):
    # 获取单个老师（GET /teacher/teacher/<id>）
    def get(self, id):
        teacher = Teacher.query.get(id)  # 根据ID查询老师
        if not teacher:
            return my_response(code=404, message='老师不存在')
        data = {'name': teacher.name, 'age': teacher.age, 'subject': teacher.subject}
        return my_response(code=200, message='查询成功', data=data)

    # 更新老师信息（PUT /teacher/teacher/<id>）
    def put(self, id):
        teacher = Teacher.query.get(id)
        if not teacher:
            return my_response(code=404, message='老师不存在')
        args = parser.parse_args()
        # 更新字段（仅更新传递的非空参数）
        teacher.name = args['name']
        teacher.age = args['age']
        teacher.subject = args['subject']
        db.session.commit()  # 提交更新
        return my_response(code=200, message='更新成功')

    # 删除老师（DELETE /teacher/teacher/<id>）
    def delete(self, id):
        teacher = Teacher.query.get(id)
        if not teacher:
            return my_response(code=404, message='老师不存在')
        db.session.delete(teacher)  # 从数据库删除
        db.session.commit()
        return my_response(code=200, message='删除成功')


# 注册路由（与前端页面请求路径保持一致）
api.add_resource(TeacherResource, '/teacher')  # 批量操作路由
api.add_resource(TeacherSingleResource, '/teacher/<int:id>')  # 单个操作路由